<template>
  <div class="order-form">
    <div class="order-form__head g-card-title">
      <span>Order Form</span>
    </div>
    <div class="order-form__body form">
      <div class="form-tab">
        <div
          class="g-clickable item"
          :class="{ buy: orderType === 'buy' }"
          @click="orderType = 'buy'"
        >
          <span>Buy</span>
        </div>
        <div
          class="g-clickable item"
          :class="{ sell: orderType === 'sell' }"
          @click="orderType = 'sell'"
        >
          <span>Sell</span>
        </div>
      </div>
      <div class="form-order-type">
        <div
          class="g-clickable item"
          :class="{ on: orderPriceType === 1 }"
          @click="orderPriceType = 1"
        >
          <span>Market</span>
        </div>
        <div
          class="g-clickable item"
          :class="{ on: orderPriceType === 2 }"
          @click="orderPriceType = 2"
        >
          <span>Limit</span>
        </div>
        <div
          class="item stop"
          :class="{ on: orderPriceType === 3 || orderPriceType === 4 }"
        >
          <span>{{
            orderPriceType === 3
              ? "Stop Limit"
              : orderPriceType === 4
              ? "Stop Market"
              : "Stop"
          }}</span>
          <i class="iconfont icon-arrow-up"></i>
          <div class="list">
            <ul>
              <li class="g-clickable" @click="orderPriceType = 3">
                <span>Stop Limit</span>
              </li>
              <li class="g-clickable" @click="orderPriceType = 4">
                <span>Stop Market</span>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div class="form-input">
        <span>Price</span>
        <div class="item">
          <input type="text" value="0.00" />
        </div>
        <span class="unit">{{ symbol.quoteAsset }}</span>
      </div>
      <div class="form-input">
        <span>Amount</span>
        <div class="item">
          <input type="text" value="0.00" />
        </div>
        <span class="unit">{{ symbol.baseAsset }}</span>
      </div>
      <div class="form-percent">
        <on-percent
          v-model="percent"
          :color="orderType === 'buy' ? 'green' : 'red'"
          :maxLeverage="maxPercent"
          :decimal="0"
          unit="%"
        />
      </div>
      <div class="form-label">
        <span>Avbl:</span>
        <span class="value">0.00 {{ symbol.quoteAsset }}</span>
      </div>
      <div class="form-label">
        <div>
          <span>Cast: </span
          ><span class="value">0.00 {{ symbol.quoteAsset }}</span>
        </div>
        <div>
          <span>Max: </span
          ><span class="value">0.00 {{ symbol.quoteAsset }}</span>
        </div>
      </div>
      <div class="form-button g-clickable">
        <span>Connect Wallet</span>
      </div>
    </div>
  </div>
</template>

<script>
import NouDialog from "@/components/common/NouDialog";
import showToast from "@/components/toast";
import OnPercent from "@/components/percent";

export default {
  name: "Transfer",
  components: { NouDialog, OnPercent },
  props: {
    bestPrice: {
      type: [Number, String],
      require: true,
    },
    userPrice: {
      type: [Number, String],
      require: true,
    },
    pairCode: {
      type: String,
      require: true,
    },
    selectedTab: {
      type: String,
      default: "open",
    },
    symbol: {
      type: Object,
      default() {
        return {};
      },
    },
    accountInfo: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      stepOptions: [
        {
          label: "25%",
          value: 0,
        },
        {
          label: "50%",
          value: 1,
        },
        {
          label: "75%",
          value: 2,
        },
        {
          label: "100%",
          value: 3,
        },
      ],
      amount: "",
      price: "",
      loading: false,
      total: "",
      orderType: "buy",
      orderPriceType: 2,
      cex_user: "",
      step: -1,
      priceScale: 4,
      volumeScale: 4,
      priceScaleRegExp: RegExp("^\\d*(\\.?\\d{0,4})"),
      volumeScaleRegExp: RegExp("^\\d*(\\.?\\d{0,4})"),
      time1: null,
      time2: null,
      quoteAsset: {},
      baseAsset: {},
      assets: [],
      instrument: {},
      openLong: {},
      openShort: {},
      positions: [],
      percent: 0,
      maxPercent: 100,
      focus: false,
    };
  },
  mounted() {
    this.price = this.bestPrice;
    this.cex_user = this.$cookies.get("user") || "";
  },
  computed: {
    amountPlaceholder() {
      const label =
        this.orderPriceType === 1
          ? this.$t("exchange_total")
          : this.$t("exchange_amount");
      const unit =
        this.orderPriceType === 1
          ? this.symbol.quoteAsset
          : this.symbol.baseAsset;
      return `${label}( 0 ${unit})`;
    },
    shortVolumn() {
      return this.openShort.volumn ? Math.abs(this.openShort.volumn) : "--";
    },
  },
  watch: {
    symbol(val) {
      this.price = this.bestPrice;
      this.cex_user = this.$cookies.get("user") || "";
      const { pricePrecision, quantityPrecision } = val || {};
      this.priceScale = pricePrecision;
      this.volumeScale = quantityPrecision;
      this.priceScaleRegExp =
        pricePrecision > 0
          ? RegExp("^\\d*(\\.?\\d{0," + pricePrecision + "})")
          : RegExp("^\\d*");
      this.volumeScaleRegExp =
        quantityPrecision > 0
          ? RegExp("^\\d*(\\.?\\d{0," + quantityPrecision + "})")
          : RegExp("^\\d*");
      this.amount = "";
      this.openLong = this.getPosition("0", this.symbol.pair);
      this.openShort = this.getPosition("1", this.symbol.pair);
      this.quoteAsset = this.getAsset(this.symbol.quoteAsset);
      this.baseAsset = this.getAsset(this.symbol.baseAsset);
    },
    accountInfo(val) {
      const { assets = [], instrument = {}, positions = [] } = val;
      this.assets = assets;
      this.instrument = instrument;
      this.positions = positions;
      this.openLong = this.getPosition("0", this.symbol.pair);
      this.openShort = this.getPosition("1", this.symbol.pair);
      this.quoteAsset = this.getAsset(this.symbol.quoteAsset);
      this.baseAsset = this.getAsset(this.symbol.baseAsset);
    },
    amount(val) {
      if (+val >= 0 && +this.price >= 0) {
        const _total = (+val * +this.price).toString();
        this.total = _total.match(this.priceScaleRegExp)[0] || null;
      } else {
        this.total = "--";
      }
    },
    orderPriceType(val) {
      this.amount = "";
      this.step = -1;
    },
    selectedTab(val) {
      this.amount = "";
      this.step = -1;
    },
    userPrice(val) {
      this.price = val;
    },
    percent(val) {
      const _percent = val / 100;
      if (this.selectedTab === "open") {
        if (this.orderPriceType === 1) {
          this.amount = this.toFix(
            this.quoteAsset.availableBalance * _percent,
            this.priceScaleRegExp
          );
        } else {
          this.amount = this.toFix(
            this.quoteAsset.availableBalance * _percent * (1 / this.price)
          );
        }
      } else if (this.selectedTab === "close") {
        this.amount = this.toFix(this.openLong.volumn * _percent);
      }
    },
  },
  methods: {
    setAmount() {
      this.percent = 0;
    },
    getCexUrl(path) {
      return this.$cexURL + (path || "");
    },
    getOOEUrl(path) {
      return this.$ooeURL + (path || "");
    },
    handleInputPrice(e) {
      clearTimeout(this.time1);
      this.time1 = setTimeout(() => {
        e.target.value = e.target.value.match(this.priceScaleRegExp)[0] || null;
      }, 300);
    },
    handleInputAmount(e) {
      clearTimeout(this.time2);
      this.time2 = setTimeout(() => {
        if (this.orderPriceType === 1 && this.selectedTab === "open") {
          e.target.value =
            e.target.value.match(this.priceScaleRegExp)[0] || null;
        } else {
          e.target.value =
            e.target.value.match(this.volumeScaleRegExp)[0] || null;
        }
      }, 300);
    },
    handleStepChange(i) {
      if (this.selectedTab === "open") {
        if (this.orderPriceType === 1) {
          this.amount = this.toFix(
            this.quoteAsset.availableBalance * (this.step + 1) * 0.25,
            this.priceScaleRegExp
          );
        } else {
          this.amount = this.toFix(
            this.quoteAsset.availableBalance *
              (this.step + 1) *
              0.25 *
              (1 / this.price)
          );
        }
      } else if (this.selectedTab === "close") {
        this.amount = this.toFix(this.openLong.volumn * (this.step + 1) * 0.25);
      }
    },
    toFix(val, scaleRegExp) {
      return +(val || "")
        .toString()
        .match(scaleRegExp || this.volumeScaleRegExp)[0];
    },
    getAsset(symbol) {
      if (!symbol || !this.assets.length) return {};
      const temp = this.assets.filter((item) => {
        return item.asset === symbol;
      });
      return (temp && temp[0]) || {};
    },
    getPosition(side, symbol) {
      if (!symbol || !this.positions.length) return {};
      const temp = this.positions.filter((item) => {
        const { positionSide, instrumentId } = item;
        return (
          positionSide === side && instrumentId.replace(/.*?_/gi, "") === symbol
        );
      });
      return (temp && temp[0]) || {};
    },
    async submit(direction) {},
  },
};
</script>
</script>

<style lang="scss" scoped>
.order-form {
  display: flex;
  flex-direction: column;
}
.form-tab {
  margin-top: 15px;
  display: flex;
  align-items: center;

  .item {
    cursor: pointer;
    flex: 1;
    height: 45px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--border-color);

    &:first-child {
      border-radius: 10px 0 0 10px;
    }

    &:last-child {
      border-radius: 0 10px 10px 0;
    }

    &.buy {
      background-color: var(--color-green);
    }

    &.sell {
      background-color: var(--color-red);
    }

    span {
      font-size: 14px;
      font-family: "Roboto Medium";
    }
  }
}
.form-order-type {
  margin-top: 10px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .item {
    cursor: pointer;
    flex: 1;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--border-color);

    &.on {
      background-color: rgba(255, 255, 255, 0.03);
    }

    &:first-child {
      border-radius: 10px 0 0 10px;
    }

    &:last-child {
      border-radius: 0 10px 10px 0;
    }

    .iconfont {
      margin: 3px 0 0 3px;
      transform: rotate(180deg) scale(0.8);
    }

    &.stop {
      position: relative;
      &:hover {
        .list {
          top: 24px;
          max-height: initial;
        }
      }
    }

    .list {
      position: absolute;
      right: 0;
      width: 96px;
      top: 20px;
      max-height: 0;
      border-radius: 0 0 10px 10px;
      background: var(--card);
      transition: all 0.3s ease;
      overflow: hidden;
    }

    ul {
      padding: 8px 0;
      background-color: rgba(255, 255, 255, 0.03);
      li {
        line-height: 32px;
        text-indent: 15px;

        &:hover {
          background-color: rgba(255, 255, 255, 0.05);
        }

        span {
          font-size: 10px;
          font-family: "Roboto Regular";
        }
      }
    }
  }
}
.form-input {
  margin-top: 10px;
  padding: 5px 0 5px 15px;
  height: 46px;
  border-radius: 10px;
  display: grid;
  align-items: center;
  grid-template-columns: 70px 1fr 50px;
  background-color: var(--border-color);

  span {
    font-size: 14px;
    font-family: "Roboto Medium";

    &.unit {
      text-align: left;
      color: var(--color-content);
    }
  }

  .item {
    input {
      width: 155px;
      background: none;
      border: none;
      outline: none;
      height: 42px;
      padding: 10px;
      line-height: 22px;
      text-align: right;
      box-sizing: border-box;

      color: var(--color);
      font-size: 14px;
      font-family: "Roboto Medium";
    }
  }
}
.form-percent {
  margin-top: 10px;
}
.form-label {
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  span {
    font-size: 12px;
    font-family: "Roboto Regular";
    color: var(--color-content);

    &.value {
      color: var(--color);
      margin-left: 3px;
    }
  }
}
.form-button {
  margin-top: 20px;
  height: 48px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10px;
  background-color: var(--color-green);
  span {
    font-size: 14px;
    font-family: "Roboto Medium";
    color: var(--color);
  }
}
</style>
